﻿using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.Scripting;
using Microsoft.Scripting.Ast;
using Microsoft.Linq.Expressions;

namespace DlrBasic.Parser.Ast
{
    class BasicProgram : ProgramBase
    {
        private Line[] lines;

        public BasicProgram(SourceSpan span, Line[] lines)
            : base(span)
        {
            this.lines = lines;
        }


        internal override void Visit(StatementsVisitor visitor)
        {
            visitor.BasicProgram(this);
            foreach (Line line in lines)
            {
                line.Visit(visitor);
            }
        }

        internal override Expression Generate(DlrBasicGenerator g)
        {
            g.GenerateStatementNumbers(this);

            return base.Generate(g);
        }

        protected override Expression CreateDebugInfo(DlrBasicGenerator g)
        {
            int[] lineNumbers = new int[lines.Length];
            int[] states = new int[lines.Length];

            for (int i = 0; i < lineNumbers.Length; i++)
            {
                lineNumbers[i] = lines[i].LineNumber;
                states[i] = g.GetStatementNumber(lines[i].GetFirstStatement());
            }

            StatementNames namesVisitor = new StatementNames();
            Visit(namesVisitor);

            Expression debugInfo = Expression.New(typeof(Runtime.DlrBasicDebugInfo).GetConstructors()[0],
                    Expression.Constant(lineNumbers), Expression.Constant(states),
                    Expression.Constant(namesVisitor.Names.ToArray()));
            return debugInfo;
        }

    }
}
